package com.cos.shop.dao.impl;

import com.cos.shop.common.Const;
import com.cos.shop.dao.AddressDao;
import com.cos.shop.entity.Address;
import com.cos.shop.util.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * Copyright (C),2021-2022,亚瑟王
 * FileName: AddressDaoImpl
 * Author: saber
 * Date:2022/9/19 21:28
 */
public class AddressDaoImpl implements AddressDao {

    private QueryRunner qr = new QueryRunner(DBUtils.getDataSource());

    @Override
    public int setDefaultAddress(int aid) throws SQLException {
        return qr.update("update address set astate = ? where aid = ?", Const.UserCode.DEFAULT_ADDRESS,aid);
    }

    @Override
    public int setAllState(int uid) throws SQLException {
        return qr.update("update address set astate = ? where uid = ?",
                Const.UserCode.NOT_DEFAULT_ADDRESS,uid);
    }

    @Override
    public int updateAddress(Address a) throws SQLException {
        return qr.update("update address set aname=?,aphone=?,adetail=? where aid = ?",
                a.getAname(),
                a.getAphone(),
                a.getAdetail(),
                a.getAid());
    }

    @Override
    public int deleteAddress(int aid) throws SQLException {
        return qr.update("delete from address where aid = ?",aid);
    }

    @Override
    public int addUserAddress(Address a) throws SQLException {
        return qr.update("insert into address values (default,?,?,?,?,?)",
                a.getUid(),
                a.getAname(),
                a.getAphone(),
                a.getAdetail(),
                a.getAstate());
    }

    @Override
    public List<Address> getUserAddress(int uid) throws SQLException {
        return qr.query("select * from address where uid = ? order by astate desc",new BeanListHandler<>(Address.class)
                ,uid);
    }

} 
